import axios from 'axios'
import 'element-plus/theme-chalk/el-message.css'
import { userInfoStore } from '@/stores/user'
import router from '@/router'
import {ElMessage} from "element-plus";

const http = axios.create({
    timeout: 30000
})


// axios请求拦截器
http.interceptors.request.use(config => {
    const useUserInfoStore = userInfoStore()
    const token = useUserInfoStore.userInfo.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }

    // // 获取URL前缀并设置baseURL
    // const urlPrefix = Object.keys(urlPrefixMap).find(prefix =>
    //     config.url?.startsWith(prefix)
    // )
    // if (urlPrefix) {
    //     config.baseURL = urlPrefixMap[urlPrefix]
    //     // 去除URL前缀，构建实际路径
    //     config.url = config.url?.replace(urlPrefix, '')
    // } else {
    //     // 如果没有匹配的前缀，使用默认的baseURL
    //     config.baseURL = import.meta.env.VITE_APP_WEB_BASE_TARGET
    // }
    return config
}, e => Promise.reject(e))

// 添加响应拦截器
http.interceptors.response.use(async (res) => {
    const data = res.data
    const useUserInfoStore = userInfoStore()
    if (data.code === 401) {
        await useUserInfoStore.clearUserInfo()
        await router.push('/login')
        ElMessage.error("登录失效请重新登录")
    } else if (data.code === 500) {
        ElMessage.error(data.message)
        return Promise.reject(res)
    }

    return data
}, async (e) => {
    const useUserInfoStore = userInfoStore()
    if (e.response?.status === 401) {
        await useUserInfoStore.clearUserInfo()
        await router.push('/login')
    }
    return Promise.reject(e)
})

export default http
